#include "../header/fudpServer.hpp"

//using namespace std;

#define BUFFER_SIZE 1024

void testServer();

int main(int argc, const char * argv[]) {
    // testServer();

    fudpServer server;

    server.listern();
    
    return 0;
}

void testServer(){
	// const char* ip = argv[1];
    
	const char* ip="0";

	int port=fltp_port;

    std::cout << "ip=" << ip << " port="<<port << std::endl;

    int fd;
    int check_ret;

    fd = socket(PF_INET,SOCK_DGRAM , 0);
    assert(fd >= 0);

    struct sockaddr_in address;
    bzero(&address,sizeof(address));

    //转换成网络地址
    address.sin_port = htons(port);
    address.sin_family = AF_INET;
    //地址转换
    inet_pton(AF_INET, ip, &address.sin_addr);

    //绑定ip和端口
    check_ret = bind(fd,(struct sockaddr*)&address,sizeof(address));
    assert(check_ret >= 0);

    while(1){

        char buffer[BUFFER_SIZE];
        struct sockaddr_in addressClient;
        socklen_t clientLen = sizeof(addressClient);
        memset(buffer, '\0', BUFFER_SIZE);
        //获取信息
        if(recvfrom(fd, buffer, BUFFER_SIZE-1,0,(struct sockaddr*)&addressClient, &clientLen) == -1) 
        { 
           perror("Receive Data Failed:"); 
           exit(1); 
        } 

        printf("buffer=%s\n", buffer);

		char response[50]="Your msg has been recieve.";

		if(sendto(fd, response, strlen(response),0,(struct sockaddr*)&addressClient,sizeof(addressClient)) < 0) 
		{
			perror("response Failed:"); 
			exit(1); 
		} else {
			printf("response succeed\n");
		}
    }
    close(fd);
}